#!/bin/bash
while read line; do
eval $line
done < Config/config

#The plotter is called from any CARBLogger driver
#It depends upon the installation of gnuplot and gnuplotfeed
cleanup()
{
    echo "Caught Signal ... cleaning up."
    if !(rm -f Data/.locked > /dev/null); then
        {
                  exit 1
        }
    fi
	my_interface=`ps -fe | grep interface | grep -v grep | awk '{ print $2 }'`  
    for i in `pgrep ${feed_id} | grep -v ${my_interface}`
    do
    	kill -9 $i 2>/dev/null
    done 
    kill -9 ${feed_id}
    echo "Done cleanup ... quitting."
     exit 0
  }
                                                                                     

########################################################
#	GET THE PATH TO THE CURRENT DRIVER THE PARAMETERS TO PLOT                   #
########################################################
#DIR returns operating directory of the testd script

DIR="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
#Plot dir Provides the CARBLogger Relative Directory
#PLOT_DIR=`echo ${DIR} | sed -s 's/\/home\/aqdms\/CARBLog//g'
#echo $PLOT_DIR
#########################################################
#	CHECK THE EXISTANCE OF NEEDED RESOURCES				#
#	MJV													#
#########################################################
if !( which feedgnuplot ); then
	{
	echo "No feedgnuplot has been found here"
	echo "exiting"
	exit 1
	}
elif !(which gnuplot); then
	{
 	echo "No gnuplot has been found here"
	echo "exiting"
	exit 1
	}
elif !( which pgrep ); then
	{
	echo "No pgrep...stopping"
	exit 1	
	}
fi
####################################################################################
#   SYNCHRONIZE 60 Sec PLOTTING CYCLE WITH FRONT DISPLAY ~ 5 sec after the top of the minute
#####################################################################################
while [ `date "+%S"` != 25 ]
do
    sleep .1
done
#CHECK FOR UNCONFIGURED DMS.CFG
#if [ ! -f sys_resources/.guid_provided ]
#then
#touch sys_resources/.guide_provided
#    xmessage 'CARBLogger uses the GNUPlot X11 terminal. Use g to toggle the grid,\
#     r for a ruler, zoom in with right clicking the mouse, p,u, and n to return\
#      to previous zoom states, a for autoscale '&
#fi
######################################################################
#	GRAB ALL OF THE DISPLAY PARAMETERS AND PLOT THEM
######################################################################
#TRAP CTRL+C
catchup="0"
trap cleanup 1 2 3 6 15
while [ : ]; do
{
	if [ $catchup -eq 0 ]; then
	{
		hour=`date '+%H'`
		minute=`date '+%M'`
		for h in `seq -w 0 $hour`
		do
		(grep "_${h}:${m}" | sed 's/--[A-Z]*//'  | sed 's/:::/  /g' | sed 's/_/  /g' | awk '(/O3BOXTEMP=/ || /O3=/){ print $2 " " $6}' | awk 'ORS=(FNR%2)?FS:RS' | awk '{ print $1" "$4","$2} ' | sed 's/O3=//g' | sed 's/O3BOXTEMP=//g')<Data/${saroad}-`date '+%Y'`-`date '+%d'`-`date '+%m'`
		catchup="1"
		done
		catchup=1
	}
	fi
	
	data=$(tail -n 1000 Data/${saroad}-`date '+%Y'`-`date '+%d'`-`date '+%m'`| grep `date '+_%H:%M'` | awk '(/O3=/ || /O3BOXTEMP=/) { print }' )  
	for i in O3=; 
	do
		if [ `date '+%H:%M'` == "01:00" ]; then
			{
				echo clear
				sleep 60
			}
			else
			{
			second_data=`echo ${data} | grep -o "O3BOXTEMP=[-,0-9].[0-9,.]*" | sed -s 's/O3BOXTEMP=//g'` 
			echo ${data} | grep -o "${i}[-,0-9].[0-9,.]*" | sed -s 's/'${i}'//g' | awk -v second="$second_data" '{ print "'`date "+%H:%M" `' "$0+0","second }'
			catchup=1				
			sleep 60
			}
		fi
	done

}
done 2>/dev/null | feedgnuplot --stream --lines --domain --xlabel 'Time [HH:MM]' --ylabel 'PPB' --y2label 'Degrees C' --timefmt '%H:%M' --extracmds 'set format x "%H:%M"; set terminal x11 noraise size 600,400 position 0,0' --points --curvestyle 0 'linewidth 2 linecolor rgb "chartreuse"' --curvestyle 1 'linewidth 2 linecolor rgb "red"' --legend 0 "O3 (left)" --legend 1 "O3 BOX TEMP(right)" --y2 1 --y2max 45 --y2min 5 --title "Ozone"
